﻿using GpCommon.Models;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI.WebControls;
using System.Windows;
using System.Xml.Linq;
using static Org.BouncyCastle.Crypto.Engines.SM2Engine;

namespace GpCommon.Helpers
{
    public class GpNetDataHelper
    {
        /// <summary>
        /// 获取最新股票数量
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async void GetGpTotalCount()
        {
            try
            {
                string url = UrlHelper.GetUrlForAllRealTimeMainData(1, 1)[0];
                using (HttpClient client = new HttpClient())
                {
                    HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false);
                    if (response.IsSuccessStatusCode)
                    {
                        response.EnsureSuccessStatusCode();
                        string htmlContent = response.Content.ReadAsStringAsync().Result;
                        if (!string.IsNullOrEmpty(htmlContent))
                        {
                            JObject jobject = JObject.Parse(htmlContent);
                            string totalStr = jobject["data"]["total"].ToString();
                            if (!string.IsNullOrEmpty(totalStr))
                            {
                                int.TryParse(totalStr, out CommonData.TotalGpCount);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }
        /// <summary>
        /// 根据代号获取股票历史日线数据
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static async Task<List<GpDayEntity>> GetHistoryDayInfoByCode(string code)
        {
            List<GpDayEntity> ents = new List<GpDayEntity>();

            string url = UrlHelper.GetUrlForSingleHistoryData(code);
            if (string.IsNullOrEmpty(url))
                return ents;
            bool hasEx = false;
            do
            {
                try
                {
                    Thread.Sleep(100);
                    HttpResponseMessage response = await HttpHelper.Client.GetAsync(url).ConfigureAwait(false);
                    if (response.IsSuccessStatusCode)
                    {
                        response.EnsureSuccessStatusCode();
                        string htmlContent = response.Content.ReadAsStringAsync().Result;
                        if (!string.IsNullOrEmpty(htmlContent))
                        {
                            JObject jobject = JObject.Parse(htmlContent);
                            var name = jobject["data"]["name"].ToString();
                            var childrens = jobject["data"]["klines"].Children();

                            foreach (var item in childrens)
                            {
                                var strs = item.ToString().Split(',');
                                if (strs.Length != 11)
                                    continue;
                                GpDayEntity ent = new GpDayEntity();
                                ent.Code = code;
                                ent.Name = name;
                                float temp = 0;
                                if (!DateTime.TryParse(strs[0].ToString(), out DateTime time))
                                    continue;
                                ent.Time = time;
                                ent.PrePrice = float.TryParse(strs[1].ToString(), out temp) ? temp : 0.0f;
                                ent.ClsPrice = float.TryParse(strs[2].ToString(), out temp) ? temp : 0.0f;
                                ent.HighPrice = float.TryParse(strs[3].ToString(), out temp) ? temp : 0.0f;
                                ent.LowPrice = float.TryParse(strs[4].ToString(), out temp) ? temp : 0.0f;
                                ent.Volume = int.TryParse(strs[5].ToString(), out int tempInt) ? tempInt : 0;
                                ent.TurnVolume = float.TryParse(strs[6].ToString(), out temp) ? temp : 0.0f;
                                ent.Amplitude = float.TryParse(strs[7].ToString(), out temp) ? temp : 0.0f;
                                ent.MarkUp = float.TryParse(strs[8].ToString(), out temp) ? temp : 0.0f;
                                ent.MarkUpPrice = float.TryParse(strs[9].ToString(), out temp) ? temp : 0.0f;
                                ent.ChangeHands = float.TryParse(strs[10].ToString(), out temp) ? temp : 0.0f;

                                ents.Add(ent);
                            }
                        }
                        hasEx = false;
                    }
                }
                catch (AggregateException)
                {
                    hasEx = true;
                }
            } while (hasEx);

            return ents;
        }

        public static async Task<List<DetailEntity>> GetGpDetail(string code)
        {
            List<DetailEntity> prices = new List<DetailEntity>();

            string url = UrlHelper.GetUrlForSingleDetailData(code);

            bool hasEx = false;
            do
            {
                try
                {
                    HttpResponseMessage response = await HttpHelper.Client.GetAsync(url).ConfigureAwait(false);
                    if (response.IsSuccessStatusCode)
                    {
                        response.EnsureSuccessStatusCode();
                        string htmlContent = response.Content.ReadAsStringAsync().Result;
                        if (!string.IsNullOrEmpty(htmlContent))
                        {
                            JObject jobject = JObject.Parse(htmlContent);
                            var PrePrice = double.Parse(jobject["data"]["prePrice"].ToString());
                            var Name = jobject["data"]["name"].ToString();
                            var trends = jobject["data"]["trends"].Children();
                            int index = 1;
                            foreach (var item in trends)
                            {
                                var strs = item.ToString().Split(',');
                                if (strs.Count() == 8)
                                {
                                    DetailEntity ent = new DetailEntity();
                                    var datesStr = strs[0].Split(' ');
                                    var dates = datesStr[0].Split('-');
                                    var times = datesStr[1].Split(':');
                                    ent.EntTimeSpan = new DateTime(int.Parse(dates[0]), int.Parse(dates[1]), int.Parse(dates[2]), int.Parse(times[0]), int.Parse(times[1]), 0);
                                    ent.Price = double.Parse(strs[2]);
                                    ent.MidPrice = double.Parse(strs[7]);
                                    double markUp = (ent.Price - PrePrice) / PrePrice * 100.00;
                                    ent.MarkUp = Math.Round(markUp, 2, MidpointRounding.AwayFromZero);
                                    double midMarkUp = (ent.MidPrice - PrePrice) / PrePrice * 100.00;
                                    ent.MidMarkUp = Math.Round(midMarkUp, 2, MidpointRounding.AwayFromZero);
                                    ent.Index = index++;
                                    prices.Add(ent);
                                }
                            }
                        }
                    }
                }
                catch (AggregateException)
                {
                    hasEx = true;
                }
            } while (hasEx);
            return prices;
        }

        /// <summary>
        /// 根据股票代号及时间获取当日分时数据
        /// </summary>
        /// <param name="time"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static async Task<List<GpDayMS_OLEntity>> GetDayMS_OLEntityByCode(DateTime time, string code)
        {
            List<GpDayMS_OLEntity> ents = new List<GpDayMS_OLEntity>();

            string url = UrlHelper.GetUrlForSingleGpHistoryDetailData(code, time);
            if (string.IsNullOrEmpty(url))
                return ents;
            string typeId = "";
            if (code.StartsWith("00"))
            {
                typeId = "SZ";
            }
            else if (code.StartsWith("60"))
            {
                typeId = "SS";
            }
            string name = code + "." + typeId;
            bool hasEx = false;
            do
            {
                try
                {
                    Thread.Sleep(100);
                    HttpResponseMessage response = await HttpHelper.Client.GetAsync(url).ConfigureAwait(true);
                    if (response.IsSuccessStatusCode)
                    {
                        response.EnsureSuccessStatusCode();
                        string htmlContent = response.Content.ReadAsStringAsync().Result;
                        if (!string.IsNullOrEmpty(htmlContent))
                        {
                            JObject jobject = JObject.Parse(htmlContent);
                            var childrens = jobject["data"]["trend"][name].Children();

                            foreach (var item in childrens)
                            {
                                var subData = item.Children().ToList();
                                string timeData = subData[0].ToString();
                                int year = int.Parse(timeData.Substring(0, 4));
                                int month = int.Parse(timeData.Substring(4, 2));
                                int day = int.Parse(timeData.Substring(6, 2));
                                int hour = int.Parse(timeData.Substring(8, 2));
                                int minute = int.Parse(timeData.Substring(10, 2));
                                GpDayMS_OLEntity ent = new GpDayMS_OLEntity();
                                ent.Time = new DateTime(year, month, day, hour, minute, 0);
                                ent.Price = float.Parse(subData[1].ToString());
                                ent.Volume = int.Parse(subData[2].ToString());
                                ent.MidPrice = float.Parse(subData[3].ToString());
                                ents.Add(ent);
                            }
                        }
                        hasEx = false;
                    }
                }
                catch (AggregateException)
                {
                    hasEx = true;
                }
            } while (hasEx);

            return ents;
        }

        /// <summary>
        /// 获取实时数据
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<List<GpCurEntity>> GetAllCurGpData()
        {
            var urls = UrlHelper.GetUrlForAllRealTimeData();
            List<GpCurEntity> ents = new List<GpCurEntity>();
            try
            {
                foreach (var url in urls)
                {
                    Thread.Sleep(100);
                    HttpResponseMessage response = await HttpHelper.Client.GetAsync(url).ConfigureAwait(false);
                    if (response.IsSuccessStatusCode)
                    {
                        response.EnsureSuccessStatusCode();
                        string htmlContent = response.Content.ReadAsStringAsync().Result;
                        if (!string.IsNullOrEmpty(htmlContent))
                        {
                            JObject jobject = JObject.Parse(htmlContent);
                            var childrens = jobject["data"]["diff"].Children();
                            string totalStr = jobject["data"]["total"].ToString();
                            if (!string.IsNullOrEmpty(totalStr))
                            {
                                int.TryParse(totalStr, out CommonData.TotalGpCount);
                            }

                            foreach (var item in childrens)
                            {
                                GpCurEntity ent = new GpCurEntity();
                                ent.Code = item["f12"].ToString();
                                ent.Name = item["f14"].ToString();
                                float tempF = 0f;
                                long tempI = 0;
                                ent.CurPrice = float.TryParse(item["f2"].ToString(), out tempF) ? tempF : 0.0f;
                                ent.CurMarkUp = float.TryParse(item["f3"].ToString(), out tempF) ? tempF : 0.0f;
                                ent.CurMarkUpValue = float.TryParse(item["f4"].ToString(), out tempF) ? tempF : 0.0f;
                                ent.Volume = CommonUtility.ToFloat((CommonUtility.ToFloat(item["f5"].ToString()) / 10000f).ToString("F2"));
                                ent.TurnVolume = CommonUtility.ToFloat((CommonUtility.ToFloat(item["f6"].ToString()) / 100000000f).ToString("F2"));
                                ent.Amplitude = float.TryParse(item["f7"].ToString(), out tempF) ? tempF : 0.0f;
                                ent.ChangeHands = float.TryParse(item["f8"].ToString(), out tempF) ? tempF : 0.0f;

                                ent.PERate = float.TryParse(item["f9"].ToString(), out tempF) ? tempF : 0.0f;
                                ent.VolumeRate = float.TryParse(item["f10"].ToString(), out tempF) ? tempF : 0.0f;
                                ent.CurAccerFor5M = float.TryParse(item["f11"].ToString(), out tempF) ? tempF : 0.0f;
                                ent.HighPrice = float.TryParse(item["f15"].ToString(), out tempF) ? tempF : 0.0f;
                                ent.LowPrice = float.TryParse(item["f16"].ToString(), out tempF) ? tempF : 0.0f;
                                ent.PrePrice = float.TryParse(item["f17"].ToString(), out tempF) ? tempF : 0.0f;
                                ent.YesClsPrice = float.TryParse(item["f18"].ToString(), out tempF) ? tempF : 0.0f;
                                var totalMarketValue = long.TryParse(item["f20"].ToString(), out tempI) ? tempI : 0;
                                ent.TotalMarketValue = CommonUtility.ToFloat((totalMarketValue / 10000000000f).ToString("F2"));
                                var moveMarketValue = long.TryParse(item["f21"].ToString(), out tempI) ? tempI : 0;
                                ent.MoveMarketValue = CommonUtility.ToFloat((moveMarketValue / 10000000000f).ToString("F2"));
                                ent.CurAccer = float.TryParse(item["f22"].ToString(), out tempF) ? tempF : 0.0f;
                                ent.PBRate = float.TryParse(item["f23"].ToString(), out tempF) ? tempF : 0.0f;
                                ent.MarkUpFor60 = float.TryParse(item["f24"].ToString(), out tempF) ? tempF : 0.0f;
                                ent.MarkUpForYear = float.TryParse(item["f25"].ToString(), out tempF) ? tempF : 0.0f;

                                ents.Add(ent);
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {

            }

            return ents;
        }

        /// <summary>
        /// 获取指定时间的昨日涨停
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static async Task<Dictionary<string, int>> GetYesTopGps(DateTime time)
        {
            int count = 20;
           
            string url = UrlHelper.GetUrlForYesTodayTopGps(time, 20);
            Dictionary<string, int>  codes = new Dictionary<string, int>();
            try
            {
                Thread.Sleep(100);
                HttpResponseMessage response = await HttpHelper.Client.GetAsync(url).ConfigureAwait(false);
                if (response.IsSuccessStatusCode)
                {
                    response.EnsureSuccessStatusCode();
                    string htmlContent = response.Content.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(htmlContent))
                    {
                        JObject jobject = JObject.Parse(htmlContent);
                        if (string.IsNullOrEmpty(jobject["data"].ToString())) return null;
                        var childrens = jobject["data"]["pool"].Children();
                        string totalStr = jobject["data"]["tc"].ToString();
                        if (!string.IsNullOrEmpty(totalStr))
                        {
                            int.TryParse(totalStr, out count);
                        }

                        foreach (var item in childrens)
                        {
                            string code = item["c"].ToString();
                            int topCount = int.Parse(item["ylbc"].ToString());
                            codes[code] = topCount;
                        }
                    }
                }

                if (count != 20)
                {
                    codes.Clear();
                    url = UrlHelper.GetUrlForYesTodayTopGps(time, count);
                    response = await HttpHelper.Client.GetAsync(url).ConfigureAwait(false);
                    if (response.IsSuccessStatusCode)
                    {
                        response.EnsureSuccessStatusCode();
                        string htmlContent = response.Content.ReadAsStringAsync().Result;
                        if (!string.IsNullOrEmpty(htmlContent))
                        {
                            JObject jobject = JObject.Parse(htmlContent);
                            if (string.IsNullOrEmpty(jobject["data"].ToString())) return null;
                            var childrens = jobject["data"]["pool"].Children();
                            string totalStr = jobject["data"]["tc"].ToString();
                            if (!string.IsNullOrEmpty(totalStr))
                            {
                                int.TryParse(totalStr, out count);
                            }

                            foreach (var item in childrens)
                            {
                                string code = item["c"].ToString();
                                int topCount = int.Parse(item["ylbc"].ToString());
                                codes[code] = topCount;
                            }
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                GpCommon.Logger.Logger.Error(ex);
            }

            return codes;
        }

        /// <summary>
        /// 获取个股所属行业
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static async Task<string> GetGpSector(string code)
        {
            string url = UrlHelper.GetUrlForGpSectorInfo(code);
            try
            {
                HttpResponseMessage response = await HttpHelper.Client.GetAsync(url).ConfigureAwait(false);
                if (response.IsSuccessStatusCode)
                {
                    response.EnsureSuccessStatusCode();
                    string htmlContent = response.Content.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(htmlContent))
                    {
                        JObject jobject = JObject.Parse(htmlContent);
                        var childrens = jobject["data"]["diff"].Children();
                        foreach (var item in childrens)
                        {
                            return item["f12"].ToString();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                GpCommon.Logger.Logger.Error(ex);
            }

            return "";
        }

        /// <summary>
        /// 获取行业排名
        /// </summary>
        /// <returns></returns>
        public static async Task<List<SectorEntity>> GetSectorRank()
        {
            List<SectorEntity> entList = new List<SectorEntity>();
            string url = UrlHelper.GetUrlForSectorRank();
            try
            {
                HttpResponseMessage response = await HttpHelper.Client.GetAsync(url).ConfigureAwait(false);
                if (response.IsSuccessStatusCode)
                {
                    response.EnsureSuccessStatusCode();
                    string htmlContent = response.Content.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(htmlContent))
                    {
                        JObject jobject = JObject.Parse(htmlContent);
                        var childrens = jobject["data"]["diff"].Children();
                        string totalStr = jobject["data"]["total"].ToString();
                        if (!string.IsNullOrEmpty(totalStr))
                        {
                            int.TryParse(totalStr, out CommonData.TotalGpSectorCount);
                        }
                        foreach (var item in childrens)
                        {
                            SectorEntity ent = new SectorEntity();
                            ent.SectorId = item["f12"].ToString();
                            ent.SectorName = item["f14"].ToString();
                            entList.Add(ent);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                GpCommon.Logger.Logger.Error(ex);
            }

            return entList;
        }

        /// <summary>
        /// 获取个股当日详细信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static async Task<GpCurEntity> GetGpCurInfoByCode(string code)
        {
            string url = UrlHelper.GetUrlForGpDetailInfo(code);
            string str = "";
            try
            {
                HttpResponseMessage response = await HttpHelper.Client.GetAsync(url).ConfigureAwait(false);
                if (response.IsSuccessStatusCode)
                {
                    response.EnsureSuccessStatusCode();
                    string htmlContent = response.Content.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(htmlContent))
                    {
                        JObject jobject = JObject.Parse(htmlContent);
                        str = htmlContent;
                        var data = jobject["data"];
                        GpCurEntity curEntity = new GpCurEntity();
                        curEntity.Code = data["f57"].ToString();
                        curEntity.Name = data["f58"].ToString();
                        curEntity.CurMarkUp = CommonUtility.ToFloat((CommonUtility.ToFloat(data["f170"].ToString()) / 100.0).ToString("F2"));
                        curEntity.CurPrice = CommonUtility.ToFloat((CommonUtility.ToFloat(data["f43"].ToString()) / 100.0).ToString("F2"));
                        curEntity.HighPrice = CommonUtility.ToFloat((CommonUtility.ToFloat(data["f44"].ToString()) / 100.0).ToString("F2"));
                        curEntity.LowPrice = CommonUtility.ToFloat((CommonUtility.ToFloat(data["f45"].ToString()) / 100.0).ToString("F2"));
                        curEntity.TopPrice = CommonUtility.ToFloat((CommonUtility.ToFloat(data["f51"].ToString()) / 100.0).ToString("F2"));
                        curEntity.BottomPrice = CommonUtility.ToFloat((CommonUtility.ToFloat(data["f52"].ToString()) / 100.0).ToString("F2"));

                        curEntity.PrePrice = CommonUtility.ToFloat((CommonUtility.ToFloat(data["f46"].ToString()) / 100.0).ToString("F2"));
                        curEntity.YesClsPrice = CommonUtility.ToFloat((CommonUtility.ToFloat(data["f60"].ToString()) / 100.0).ToString("F2")); 
                        curEntity.Volume = CommonUtility.ToFloat((CommonUtility.ToFloat(data["f47"].ToString()) / 10000f).ToString("F2"));
                        curEntity.TurnVolume = CommonUtility.ToFloat((CommonUtility.ToFloat(data["f48"].ToString()) / 100000000f).ToString("F2"));
                        curEntity.Sale1Price = long.TryParse(data["f39"].ToString(), out long tempI) ? tempI / 100f : 0;
                        curEntity.Sale1Volume = long.TryParse(data["f40"].ToString(), out tempI) ? tempI : 0;
                        curEntity.Buy1Price = long.TryParse(data["f19"].ToString(), out tempI) ? tempI / 100f : 0;
                        curEntity.Buy1Volume = long.TryParse(data["f20"].ToString(), out tempI) ? tempI : 0;

                        curEntity.PERate = CommonUtility.ToFloat((CommonUtility.ToFloat(data["f162"].ToString()) / 100.0).ToString("F2"));
                        curEntity.PBRate = CommonUtility.ToFloat((CommonUtility.ToFloat(data["f167"].ToString()) / 100.0).ToString("F2"));
                        curEntity.TotalMarketValue = CommonUtility.ToFloat((CommonUtility.ToFloat(data["f116"].ToString()) / 100000000f).ToString("F2"));
                        curEntity.MoveMarketValue = CommonUtility.ToFloat((CommonUtility.ToFloat(data["f117"].ToString()) / 100000000f).ToString("F2"));

                        curEntity.HighMarkup = (float)Math.Round((curEntity.HighPrice - curEntity.YesClsPrice) / curEntity.YesClsPrice * 100.0, 2, MidpointRounding.AwayFromZero);
                        curEntity.LowMarkup = (float)Math.Round((curEntity.LowPrice - curEntity.YesClsPrice) / curEntity.YesClsPrice * 100.0, 2, MidpointRounding.AwayFromZero);

                        curEntity.ChangeHands = CommonUtility.ToFloat((CommonUtility.ToFloat(data["f168"].ToString()) / 100.0).ToString("F2")); 
                        curEntity.VolumeRate = CommonUtility.ToFloat((CommonUtility.ToFloat(data["f50"].ToString()) / 100.0).ToString("F2")); 

                        return curEntity;
                    }
                }
            }
            catch (Exception ex)
            {
                str = str + "";
                GpCommon.Logger.Logger.Error(ex);
            }
            return null;
        }

        /// <summary>
        /// 获取符合指定条件的股票数量
        /// </summary>
        /// <param name="minPrice"></param>
        /// <param name="maxPrice"></param>
        /// <param name="minRate"></param>
        /// <param name="maxRate"></param>
        /// <returns></returns>
        public static async Task<int> GetGpCountByFilter(float minPrice, float maxPrice, float minRate, float maxRate)
        {
            var url = UrlHelper.GetUrlForAllRealTimeDataByFilter(minPrice, maxPrice, minRate, maxRate, 1);
            string str = "";
            int count = 0;
            try
            {
                HttpResponseMessage response = await HttpHelper.Client.GetAsync(url).ConfigureAwait(false);
                if (response.IsSuccessStatusCode)
                {
                    response.EnsureSuccessStatusCode();
                    string htmlContent = response.Content.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(htmlContent))
                    {
                        JObject jobject = JObject.Parse(htmlContent);
                        str = htmlContent;
                        count = int.Parse(jobject["result"]["count"].ToString());
                        return count;
                    }
                }
            }
            catch (Exception ex)
            {
                str = str + "";
                GpCommon.Logger.Logger.Error(ex);
            }
            return count;
        }

        /// <summary>
        /// 获取指定股票的分时数据
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static async Task<List<DetailEntity>> GetGpTrentsByCode(string code)
        {
            List<DetailEntity> ents = new List<DetailEntity>();
            try
            {
                string url = UrlHelper.GetUrlForSingleDetailDataWithPre(code);

                HttpResponseMessage response = await HttpHelper.Client.GetAsync(url).ConfigureAwait(false);
                if (response.IsSuccessStatusCode)
                {
                    response.EnsureSuccessStatusCode();
                    string htmlContent = response.Content.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(htmlContent))
                    {
                        JObject jobject = JObject.Parse(htmlContent);
                        var prePrice = double.Parse(jobject["data"]["prePrice"].ToString());
                        var name = jobject["data"]["name"].ToString();
                        var trends = jobject["data"]["trends"].Children();
                        int index = 1;
                        foreach (var item in trends)
                        {
                            var strs = item.ToString().Split(',');
                            if (strs.Count() == 8)
                            {
                                DetailEntity ent = new DetailEntity();
                                var datesStr = strs[0].Split(' ');
                                var dates = datesStr[0].Split('-');
                                var times = datesStr[1].Split(':');
                                ent.EntTimeSpan = new DateTime(int.Parse(dates[0]), int.Parse(dates[1]), int.Parse(dates[2]), int.Parse(times[0]), int.Parse(times[1]), 0);
                                ent.Price = double.Parse(strs[2]);
                                ent.MidPrice = double.Parse(strs[7]);
                                double markUp = (ent.Price - prePrice) / prePrice * 100.00;
                                ent.MarkUp = Math.Round(markUp, 2, MidpointRounding.AwayFromZero);
                                double midMarkUp = (ent.MidPrice - prePrice) / prePrice * 100.00;
                                ent.MidMarkUp = Math.Round(midMarkUp, 2, MidpointRounding.AwayFromZero);
                                ent.Index = index++;
                                ents.Add(ent);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                GpCommon.Logger.Logger.Error(ex);
            }
            return ents;
        }

        private static int m_notionCount = 100;
        /// <summary>
        /// 获取概念板块排名
        /// </summary>
        /// <returns></returns>
        public static async Task<List<NotionEntity>> GetNotionRank()
        {
            List<NotionEntity> ents = new List<NotionEntity>();
            try
            {
                if (m_notionCount == 100)
                {
                    string url = UrlHelper.GetUrlForNotionRank(m_notionCount, 1);
                    string htmlContent = "";
                    HttpResponseMessage response = await HttpHelper.Client.GetAsync(url).ConfigureAwait(false);
                    if (response.IsSuccessStatusCode)
                    {
                        response.EnsureSuccessStatusCode();
                        htmlContent = response.Content.ReadAsStringAsync().Result;
                        if (!string.IsNullOrEmpty(htmlContent))
                        {
                            JObject jobject = JObject.Parse(htmlContent);
                            var total = CommonUtility.ToInt32(jobject["data"]["total"].ToString());
                            if (total != m_notionCount)
                            {
                                m_notionCount = total;
                            }
                        }
                    }
                }  
                
                if (m_notionCount != 100)
                {
                    var pg = m_notionCount / 100;
                    pg = m_notionCount % 100 > 0 ? pg + 1 : pg;

                    for (int i = 1; i <= pg; i++)
                    {
                        Thread.Sleep(100);
                        string url = UrlHelper.GetUrlForNotionRank(100, i);
                        string htmlContent = "";
                        HttpResponseMessage response = await HttpHelper.Client.GetAsync(url).ConfigureAwait(false);
                        if (response.IsSuccessStatusCode)
                        {
                            response.EnsureSuccessStatusCode();
                            htmlContent = response.Content.ReadAsStringAsync().Result;
                            if (!string.IsNullOrEmpty(htmlContent))
                            {
                                JObject jobject = JObject.Parse(htmlContent);
                                var trends = jobject["data"]["diff"].Children();
                                int index = 1;
                                foreach (var item in trends)
                                {
                                    NotionEntity ent = new NotionEntity();
                                    ent.Rank = index++;
                                    ent.Code = item["f12"].ToString();
                                    ent.Name = item["f14"].ToString();
                                    ent.CurMarkUp = CommonUtility.ToFloat((CommonUtility.ToFloat(item["f3"].ToString()) / 100.0).ToString("F2"));
                                    ent.CurMarkUpValue = CommonUtility.ToFloat((CommonUtility.ToFloat(item["f4"].ToString()) / 100.0).ToString("F2"));
                                    ent.CurPrice = CommonUtility.ToFloat((CommonUtility.ToFloat(item["f2"].ToString()) / 100.0).ToString("F2"));
                                    ent.TotalMarketValue = CommonUtility.ToFloat((CommonUtility.ToFloat(item["f20"].ToString()) / 100000000f).ToString("F2"));
                                    ent.ChangeHands = CommonUtility.ToFloat((CommonUtility.ToFloat(item["f8"].ToString()) / 100.0).ToString("F2"));
                                    ent.UpCount = CommonUtility.ToInt32(item["f104"].ToString());
                                    ent.DownCount = CommonUtility.ToInt32(item["f105"].ToString());
                                    ent.TopCode1 = item["f140"].ToString();
                                    ent.TopCode2 = item["f208"].ToString();
                                    ents.Add(ent);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                GpCommon.Logger.Logger.Error(ex);
            }
            return ents;
        }

        /// <summary>
        /// 获取指定概念板块的成分股数据
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<List<GpCurEntity>> GetNotionMembersByCode(string code, int count)
        {
            string url = UrlHelper.GetUrlForNotionMembersByCode(code, count);
            List<GpCurEntity> ents = new List<GpCurEntity>();
            try
            {
                Thread.Sleep(100);
                HttpResponseMessage response = await HttpHelper.Client.GetAsync(url).ConfigureAwait(false);
                if (response.IsSuccessStatusCode)
                {
                    response.EnsureSuccessStatusCode();
                    string htmlContent = response.Content.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(htmlContent))
                    {
                        JObject jobject = JObject.Parse(htmlContent);
                        var childrens = jobject["data"]["diff"].Children();

                        foreach (var item in childrens)
                        {
                            GpCurEntity ent = new GpCurEntity();
                            ent.Code = item["f12"].ToString();
                            ent.Name = item["f14"].ToString();
                            float tempF = 0f;
                            long tempI = 0;
                            ent.CurPrice = CommonUtility.ToFloat((float.TryParse(item["f2"].ToString(), out tempF) ? tempF / 100.0 : 0.0f).ToString("F2"));
                            ent.CurMarkUp = CommonUtility.ToFloat((float.TryParse(item["f3"].ToString(), out tempF) ? tempF / 100.0 : 0.0f).ToString("F2"));
                            ent.CurMarkUpValue = CommonUtility.ToFloat((float.TryParse(item["f4"].ToString(), out tempF) ? tempF / 100.0 : 0.0f).ToString("F2"));
                            ent.Volume = CommonUtility.ToFloat((CommonUtility.ToFloat(item["f5"].ToString()) / 10000f).ToString("F2"));
                            ent.TurnVolume = CommonUtility.ToFloat((CommonUtility.ToFloat(item["f6"].ToString()) / 100000000f).ToString("F2"));
                            ent.Amplitude = CommonUtility.ToFloat((float.TryParse(item["f7"].ToString(), out tempF) ? tempF / 100.0 : 0.0f).ToString("F2"));
                            ent.ChangeHands = CommonUtility.ToFloat((float.TryParse(item["f8"].ToString(), out tempF) ? tempF / 100.0 : 0.0f).ToString("F2"));

                            ent.PERate = CommonUtility.ToFloat((float.TryParse(item["f9"].ToString(), out tempF) ? tempF / 100.0 : 0.0f).ToString("F2"));
                            ent.VolumeRate = CommonUtility.ToFloat((float.TryParse(item["f10"].ToString(), out tempF) ? tempF / 100.0 : 0.0f).ToString("F2"));
                            ent.HighPrice = CommonUtility.ToFloat((float.TryParse(item["f15"].ToString(), out tempF) ? tempF / 100.0 : 0.0f).ToString("F2"));
                            ent.LowPrice = CommonUtility.ToFloat((float.TryParse(item["f16"].ToString(), out tempF) ? tempF / 100.0 : 0.0f).ToString("F2"));
                            ent.PrePrice = CommonUtility.ToFloat((float.TryParse(item["f17"].ToString(), out tempF) ? tempF / 100.0 : 0.0f).ToString("F2"));
                            ent.YesClsPrice = CommonUtility.ToFloat((float.TryParse(item["f18"].ToString(), out tempF) ? tempF / 100.0 : 0.0f).ToString("F2"));

                            ents.Add(ent);
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }

            return ents;
        }

        /// <summary>
        /// 获取指定股票的概念板块信息
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static async Task<List<string>> GetGpNotionByCode(string code)
        {
            List<string> res = new List<string>();
            string url = UrlHelper.GetUrlForGpNotionByCode(code);
            List<GpCurEntity> ents = new List<GpCurEntity>();
            try
            {
                Thread.Sleep(100);
                HttpResponseMessage response = await HttpHelper.Client.GetAsync(url).ConfigureAwait(false);
                if (response.IsSuccessStatusCode)
                {
                    response.EnsureSuccessStatusCode();
                    string htmlContent = response.Content.ReadAsStringAsync().Result;
                    if (!string.IsNullOrEmpty(htmlContent))
                    {
                        JObject jobject = JObject.Parse(htmlContent);
                        var count = CommonUtility.ToInt32(jobject["result"]["count"].ToString());
                        var childrens = jobject["result"]["data"].Children();

                        foreach (var item in childrens)
                        {
                            res.Add(item["NEW_BOARD_CODE"].ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }

            return res;
        }
    }
}
